from django.shortcuts import render, HttpResponse, redirect, reverse
from xadmin.forms import template
from xadmin.models import Templates
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from django.contrib.auth.decorators import login_required
import os
from django.conf import settings

from xadmin.plugins.auditlog import add_log


@login_required
def template_list(request):
    siteid = request.GET.get('siteid')
    mbx = ('模版管理', )
    template_list = Templates.objects.filter(site_id=siteid)
    context = {
        'siteid': siteid,
        'template_list': template_list,
        'mbx': mbx
    }
    return render(request, 'xadmin/template/list.html', context)


@login_required
def template_add(request):
    siteid = request.GET.get('siteid')
    mbx = ('模版管理', '添加模版')
    if request.method == 'GET':
        template_form = template.TemplatesForm()
        context = {
            'siteid': siteid,
            'template_form': template_form,
            'mbx': mbx
        }
        return render(request, 'xadmin/template/add.html', context)
    else:
        f = template.TemplatesForm(request.POST, request.FILES)
        new_template = f.save(commit=False)
        new_template.site_id = siteid
        new_template.save()
        action = '添加了模版《%s》' % new_template.name
        add_log(request, action, siteid)
        return redirect('%s?siteid=%s' % (reverse('templatelist'), siteid))


@login_required
def template_edit(request, templateid):
    siteid = request.GET.get('siteid')
    mbx = ('模版管理', '编辑模版')
    template_obj = Templates.objects.get(id=templateid)
    if request.method == 'GET':
        template_form = template.TemplatesForm(instance=template_obj)
        context = {
            'siteid': siteid,
            'template_form': template_form,
            'mbx': mbx
        }
        return render(request, 'xadmin/template/add.html', context)
    else:
        f = template.TemplatesForm(request.POST, request.FILES, instance=template_obj)
        if f.is_valid():
            f.save()
            action = '编辑了模版《%s》' % f.cleaned_data['name']
            add_log(request, action, siteid)
            return redirect('%s?siteid=%s' % (reverse('templatelist'), siteid))
        else:
            context = {
                'template_form': f,
                'mbx': mbx
            }
            return render(request, '%s?siteid=%s' % (reverse('templateedit', kwargs={'templateid': template_obj.id}), siteid), context)


@login_required
@require_POST
def template_del(request):
    templateid = request.POST.get('templateid')
    template_obj = Templates.objects.get(id=templateid)
    mess = {}
    try:
        template_obj.delete()
        mess['status'] = '200'
        mess['message'] = '删除成功'
        action = '删除了模版《%s》' % template_obj.name
        add_log(request, action, template_obj.site_id)
    except Exception as e:
        mess['status'] = '500'
        mess['message'] = '删除失败'
    return JsonResponse(mess)


@login_required
@require_POST
def templates_del(request):
    siteid = request.GET.get('siteid')
    mess = {}
    try:
        templateids = request.POST.get('templateids')
        temps = Templates.objects.filter(id__in=templateids.split(','))
        temps.delete()
        mess['status'] = '200'
        mess['msg'] = '删除成功'
        action = '删除了模版 %s' % ','.join(['《%s》' % x.name for x in temps])
        add_log(request, action, siteid)
    except:
        mess['status'] = '500'
        mess['msg'] = '删除失败'
    return JsonResponse(mess)


@login_required
def edit_code(request, templateid):
    siteid = request.GET.get('siteid')
    template_obj = Templates.objects.get(id=templateid)
    if request.method == 'GET':
        mbx = ('编辑模板', template_obj.name)
        temp_path = settings.TEMPLATES[0]['DIRS'][0]
        file_path = os.path.join(temp_path, template_obj.path)
        f = open(file_path, 'r', encoding='UTF-8')
        code = f.read()
        f.close()

        context = {
            'mbx': mbx,
            'template_obj': template_obj,
            'siteid': siteid,
            'code': code,
            'filepath': file_path,
        }
        return render(request, 'xadmin/template/editcode.html', context)
    else:
        file_path = request.POST.get('filepath')
        code = request.POST.get('code')
        if file_path and code:
            with open(file_path, 'w', encoding='UTF-8') as f:
                f.write(code.strip('\n'))
        return redirect('%s?siteid=%s' % (reverse('templatelist'), siteid))

